package com.pai4j.zwiki.repository;

import com.pai4j.zwiki.domain.entity.ZWikiTaskQueueEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * ZWiki任务队列Repository
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Repository
public interface ZWikiTaskQueueRepository extends JpaRepository<ZWikiTaskQueueEntity, Long> {

    /**
     * 根据任务ID查找
     */
    Optional<ZWikiTaskQueueEntity> findByTaskId(String taskId);

    /**
     * 查询待处理任务（按优先级和创建时间排序）
     */
    @Query("SELECT t FROM ZWikiTaskQueueEntity t WHERE t.status = 'pending' " +
           "ORDER BY t.priority DESC, t.createdAt ASC")
    List<ZWikiTaskQueueEntity> findPendingTasksOrderByPriority();

    /**
     * 查询用户的所有任务
     */
    List<ZWikiTaskQueueEntity> findByUserIdOrderByCreatedAtDesc(Long userId);

    /**
     * 查询指定状态的任务
     */
    List<ZWikiTaskQueueEntity> findByStatus(String status);

    /**
     * 查询超时的处理中任务（超过指定时间仍在处理）
     */
    @Query("SELECT t FROM ZWikiTaskQueueEntity t WHERE t.status = 'processing' " +
           "AND t.startedAt < :timeoutThreshold")
    List<ZWikiTaskQueueEntity> findTimeoutProcessingTasks(@Param("timeoutThreshold") LocalDateTime timeoutThreshold);

    /**
     * 查询需要重试的失败任务
     */
    @Query("SELECT t FROM ZWikiTaskQueueEntity t WHERE t.status = 'failed' " +
           "AND t.retryCount < t.maxRetryCount " +
           "ORDER BY t.priority DESC, t.updatedAt ASC")
    List<ZWikiTaskQueueEntity> findRetryableTasks();

    /**
     * 统计用户的队列中任务数
     */
    @Query("SELECT COUNT(t) FROM ZWikiTaskQueueEntity t WHERE t.userId = :userId " +
           "AND t.status IN ('pending', 'processing')")
    Long countUserQueuedTasks(@Param("userId") Long userId);

    /**
     * 统计队列总任务数
     */
    @Query("SELECT COUNT(t) FROM ZWikiTaskQueueEntity t WHERE t.status IN ('pending', 'processing')")
    Long countTotalQueuedTasks();
}

